package com.lj.app.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.JSONUtil;
import com.lj.common.exception.CommonException;
import com.lj.common_web.annotation.RequestBodyDecrypt;
import com.lj.common_web.annotation.ResponseBodyEncrypt;
import com.lj.common_web.request.RequestBodyDecipher;
import com.lj.common_web.response.ResponseBodyEncipher;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;

/**
 * @author luojing
 * @since 2025/5/30 16:38
 */
//@Component
public class AesResponseBodyEncipher implements ResponseBodyEncipher, RequestBodyDecipher {

    private static final byte[] AES_KEY = Base64.decode("VoDA1Y+Ef536q0tzM0ffcQ==");
    private static final SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, AES_KEY);

    @Override
    public Object encrypt(Object body, MethodParameter parameter, ResponseBodyEncrypt annotation) {
        if (body == null) {
            return body;
        }
        String result;
        if (body instanceof String) {
            result = (String) body;
        } else {
            // 对象转换为json字符串
            result = JSONUtil.toJsonStr(body);
        }
        // 这里使用的是aes对称加密，真实的加/解密逻辑由业务而定
        return aes.encryptHex(result);
    }

    @Override
    public String decrypt(String body, MethodParameter parameter, RequestBodyDecrypt annotation) {
        try {
            return aes.decryptStr(body);
        } catch (Exception e) {
            throw new CommonException("接口解密错误!");
        }
    }
}
